<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>jdk8新特性--Optional | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="每天一篇面试小知识  本篇着重介绍一下 Optional 类   写在前面 什么是 optional 类？ Optional 类是 Java8 新引进的一个主要用于解决的问题是 空指针异常（NullPointerException）的一个类。 Optional 类使得 Java 实现函数式编程，并且帮助在范式中实现。">
<meta property="og:type" content="article">
<meta property="og:title" content="jdk8新特性--Optional">
<meta property="og:url" content="https://curry3035.gitee.io/posts/57459/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="每天一篇面试小知识  本篇着重介绍一下 Optional 类   写在前面 什么是 optional 类？ Optional 类是 Java8 新引进的一个主要用于解决的问题是 空指针异常（NullPointerException）的一个类。 Optional 类使得 Java 实现函数式编程，并且帮助在范式中实现。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-09-12T01:00:00.000Z">
<meta property="article:modified_time" content="2022-05-26T18:19:35.341Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="进阶">
<meta property="article:tag" content="optional类">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/57459/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'jdk8新特性--Optional',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-27 02:19:35'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">jdk8新特性--Optional</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-09-12T01:00:00.000Z" title="发表于 2021-09-12 09:00:00">2021-09-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-26T18:19:35.341Z" title="更新于 2022-05-27 02:19:35">2022-05-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/jdk8%E6%96%B0%E7%89%B9%E6%80%A7/">jdk8新特性</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="jdk8新特性--Optional"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>每天一篇面试小知识</p>
</blockquote>
<p><strong>本篇着重介绍一下 Optional 类</strong></p>
<hr>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-09-21_02-13-06.png"></p>
<p><strong>写在前面</strong></p>
<p><font color=#FF8C00>什么是 optional 类？</font></p>
<p>Optional 类是 Java8 新引进的一个主要用于解决的问题是 <font color=#FF0000>空指针异常（NullPointerException）</font>的一个类。</p>
<p>Optional 类使得 Java 实现函数式编程，并且帮助在范式中实现。</p>
<span id="more"></span>



<h3 id="Optional-类简介"><a href="#Optional-类简介" class="headerlink" title="Optional 类简介"></a>Optional 类简介</h3><p>Optional 是 JDK8 新增加的一个工具类，位于 <code>java.util</code> 包下。</p>
<p>Optional 类是一个可以为 null 的容器对象。如果值存在则<code> isPresent()</code>方法会返回 true，<font color=#FF8C00>调用 get() 方法会返回该对象;</font></p>
<p>Optional 是个容器：它可以保存类型 T 的值，或者仅仅保存 null。Optional 提供很多有用的方法，这样我们就不用显式进行空值检测;</p>
<p>Optional 类的引入很好的解决空指针异常;</p>
<h3 id="Optional-类的使用"><a href="#Optional-类的使用" class="headerlink" title="Optional 类的使用"></a>Optional 类的使用</h3><h4 id="Optional-类介绍"><a href="#Optional-类介绍" class="headerlink" title="Optional 类介绍"></a>Optional 类介绍</h4><p>JDK8 新增了 Optional 类， Optional 类是一个<strong>没有子类的工具类</strong>。我们可以把 Optional 类看作是一个容器。这个容器它有两种情况：①要么有值 ②要么为null。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-09-21_02-21-53.png" style="zoom:80%;" />

<hr>
<h4 id="Optional-类的由来"><a href="#Optional-类的由来" class="headerlink" title="Optional 类的由来"></a>Optional 类的由来</h4><p><strong>在 Java 8 之前，任何访问对象方法或属性的调用都可能导致 NullPointerException</strong></p>
<p><strong>举个荔枝：</strong></p>
<p><strong>有一个 Person 类对象</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String address;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Person</span><span class="params">(String name, Integer age, String address)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">        <span class="built_in">this</span>.age = age;</span><br><span class="line">        <span class="built_in">this</span>.address = address;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getAge</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAge</span><span class="params">(Integer age)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getAddress</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> address;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAddress</span><span class="params">(String address)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.address = address;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Person&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;name=&#x27;&quot;</span> + name + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, age=&quot;</span> + age +</span><br><span class="line">                <span class="string">&quot;, address=&#x27;&quot;</span> + address + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<p><strong>对 Person 为 null 的处理方式</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Person</span> <span class="variable">person</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;curry&quot;</span>, <span class="number">30</span>, <span class="string">&quot;Golden State Warriors&quot;</span>);</span><br><span class="line">        <span class="type">Person</span> <span class="variable">person2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (person2 != <span class="literal">null</span>) &#123;</span><br><span class="line">            System.out.println(person2);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;person2为空&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<p><strong>结果</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">person为空</span><br></pre></td></tr></table></figure>



<p><strong>在 Java 8 之后，Optional 类的出现使得这一切发生了改变</strong></p>
<p><strong>举个荔枝：</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//创建 Optional 类，共有如下 3 种方式：</span></span><br><span class="line"><span class="comment">//1.创建一个 Optional 实例</span></span><br><span class="line">Optional.of(T t);</span><br><span class="line"><span class="comment">//2.创建一个空的 Optional 实例</span></span><br><span class="line">Optional.empty();</span><br><span class="line"><span class="comment">//3.若 t 不为 null，创建 Optional实例，否则创建空实例</span></span><br><span class="line">Optional.ofNullable(T t);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//1.1 通过Optional.of() 方法,只能传入一个具体指,不能传入null,传入null报空指针异常</span></span><br><span class="line">        Optional&lt;String&gt; op1 = Optional.of(<span class="string">&quot;curry&quot;</span>);</span><br><span class="line"><span class="comment">//        Optional&lt;Object&gt; op2 = Optional.of(null);</span></span><br><span class="line">        System.out.println(op1);<span class="comment">//Optional[Lucy]</span></span><br><span class="line"><span class="comment">//        System.out.println(op2);//java.lang.NullPointerException</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.2 通过Optional.ofNullable()方法(可以传入具体值,也可以传入null,并不会报空指针异常)</span></span><br><span class="line">        Optional&lt;String&gt; op3 = Optional.ofNullable(<span class="string">&quot;curry&quot;</span>);</span><br><span class="line">        Optional&lt;Object&gt; op4 = Optional.ofNullable(<span class="literal">null</span>);</span><br><span class="line">        System.out.println(op3);<span class="comment">//Optional[Lucy]</span></span><br><span class="line">        System.out.println(op4);<span class="comment">//Optional.empty</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.3 通过 Optional.empty() 方法创建一个空 Optional,存入的是null</span></span><br><span class="line">        Optional&lt;Object&gt; op5 = Optional.empty();</span><br><span class="line">        System.out.println(op5);<span class="comment">//Optional.empty</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<p><strong>结果</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Optional[curry]</span><br><span class="line">Optional[curry]</span><br><span class="line">Optional.empty</span><br><span class="line">Optional.empty</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="Optional-类常用方法"><a href="#Optional-类常用方法" class="headerlink" title="Optional 类常用方法"></a>Optional 类常用方法</h3><h4 id="私有构造"><a href="#私有构造" class="headerlink" title="私有构造"></a>私有构造</h4><p>在 Optional 类中，构造函数被私有访问修饰符修饰，也就意味着我们无法使用 <code>new</code> 关键字来创建对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="title function_">Optional</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="empty"><a href="#empty" class="headerlink" title="empty()"></a>empty()</h4><p>使用 <code>Optional</code> 类的静态方法 <code>empty()</code> ，可以创建一个容器内值为 <code>null</code> 的 <code>Optional</code> 对象。使用该方法，得到的 <code>Optional</code> 类是存在的，只不过该类中的值为 <code>null</code></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        Optional&lt;User&gt; empty = Optional.empty();</span><br><span class="line">        System.out.println(empty != <span class="literal">null</span>);</span><br><span class="line">        System.out.println(empty);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="of-T-value"><a href="#of-T-value" class="headerlink" title="of (T value)"></a>of (T value)</h4><p><code>of(T value)</code> 方法是 <code>Optional</code> 类创建容器的主要方法，使用该方法，可以创建一个泛型为 <code>T</code> 的 <code>Optional</code> 容器，并向容器内注入一个值对象</p>
<p>需要注意的是，使用 <code>of(T value)</code> 方法，<font color=#FF0000>参数不可以为 null，否则程序会报空指针异常</font></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.of(user1);</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="comment">//Optional&lt;User&gt; optionalUser2 = Optional.of(user2);</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="ofNullable-T-value-★"><a href="#ofNullable-T-value-★" class="headerlink" title="ofNullable (T value) ★"></a>ofNullable (T value) ★</h4><p><code>ofNullable(T value)</code> 方法和 <code>of(T value)</code> 方法唯一的区别在于，参数可以为 <code>null</code>，如果参数为 <code>null</code>，会调用 <code>empty()</code> 方法返回一个空的 <code>Optional</code> 对象，推荐此方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        Optional&lt;User&gt; optionalUser2 = Optional.ofNullable(user2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="get"><a href="#get" class="headerlink" title="get()"></a>get()</h4><p><code>get()</code> 方法，用于返回 <code>Optional</code> 容器中的值对象。但是如果 <code>Optional</code> 容器为一个空容器，即内部的值为 <code>null</code>，则会抛出 <code>NoSuchElementException</code> 异常</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        optionalUser1.get();</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        Optional&lt;User&gt; optionalUser2 = Optional.ofNullable(user2);</span><br><span class="line">        optionalUser2.get();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="isPresent"><a href="#isPresent" class="headerlink" title="isPresent()"></a>isPresent()</h4><p><code>isPresent()</code> 方法，用于判断 <code>Optional</code> 容器内是否有值，有则返回 <code>true</code>，否则返回 <code>false</code></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        System.out.println(optionalUser1.isPresent());</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        Optional&lt;User&gt; optionalUser2 = Optional.ofNullable(user2);</span><br><span class="line">        System.out.println(optionalUser2.isPresent());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="ifPresent-Consumer-lt-super-T-gt-consumer"><a href="#ifPresent-Consumer-lt-super-T-gt-consumer" class="headerlink" title="ifPresent(Consumer&lt;? super T&gt; consumer)"></a>ifPresent(Consumer&lt;? super T&gt; consumer)</h4><p><code>ifPresent(Consumer consumer)</code> 方法，参数是一个消费型函数式接口，可以配合 Lambda 表达式使用。<br>该方法的作用为：如果 <code>Optional</code> 容器中有值，则执行 <code>Consumer</code> 接口中的方法，否则不做其他任何操作。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        optionalUser1.ifPresent((o) -&gt; System.out.println(o));</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        Optional&lt;User&gt; optionalUser2 = Optional.ofNullable(user2);</span><br><span class="line">        optionalUser2.ifPresent((o) -&gt; System.out.println(o));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="filter-Predicate-lt-super-T-gt-predicate"><a href="#filter-Predicate-lt-super-T-gt-predicate" class="headerlink" title="filter(Predicate&lt;? super T&gt; predicate)"></a>filter(Predicate&lt;? super T&gt; predicate)</h4><p><code>filter(Predicate predicate)</code> 方法用于过滤 <code>Optional</code> 容器中的值，如果 容器内的值符合 <code>Predicate</code> 函数所定义的接口，即返回 <code>true</code>，则返回原来的 <code>Optional</code> 对象，否则返回空的 <code>Optional</code> 容器对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user1.setUsername(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        System.out.println(optionalUser1.filter((o) -&gt; o.getUsername().equals(<span class="string">&quot;zhangsan&quot;</span>)));</span><br><span class="line"></span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user2.setUsername(<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        Optional&lt;User&gt; optionalUser2 = Optional.ofNullable(user2);</span><br><span class="line">        System.out.println(optionalUser2.filter((o) -&gt; o.getUsername().equals(<span class="string">&quot;zhangsan&quot;</span>)));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="map-Function-lt-super-T-extends-U-gt-mapper"><a href="#map-Function-lt-super-T-extends-U-gt-mapper" class="headerlink" title="map(Function&lt;? super T, ? extends U&gt; mapper)"></a>map(Function&lt;? super T, ? extends U&gt; mapper)</h4><p><code>map(Function mapper)</code> 方法，可以将 <code>Optional</code> 容器内的值替换为其他类型的值，具体的替换规则由 <code>Function</code> 函数定义</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user1.setUsername(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        System.out.println(optionalUser1.map((o) -&gt; o.getUsername()).get());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="flatMap-Function-lt-super-T-Optional-gt-mapper"><a href="#flatMap-Function-lt-super-T-Optional-gt-mapper" class="headerlink" title="flatMap(Function&lt;? super T, Optional&gt; mapper)"></a>flatMap(Function&lt;? super T, Optional&gt; mapper)</h4><p>该方法与 <code>map(Function mapper)</code> 方法类似，不过该方法要求在 <code>Function</code> 函数中返回 <code>Optional</code> 对象，并且返回的 <code>Optional</code> 对象不允许为 <code>null</code></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user1.setUsername(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        System.out.println(optionalUser1.flatMap((o) -&gt; Optional.ofNullable(o.getUsername())).get());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="orElse-T-other"><a href="#orElse-T-other" class="headerlink" title="orElse(T other)"></a>orElse(T other)</h4><p><code>orElse(T other)</code> 方法和 <code>get()</code> 方法类似，不过比 <code>get()</code> 方法多了一层保险机制，如果 <code>Optional</code> 容器中的值为 <code>null</code>，则会返回 <code>orElse(T other)</code> 方法参数中的对象，该参数类型必须和 <code>Optional</code> 泛型类型一致</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">         <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">         Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">         <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> optionalUser1.orElse(<span class="keyword">new</span> <span class="title class_">User</span>());</span><br><span class="line">         System.out.println(user1 == user2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="orElseGet-Supplier-lt-extends-T-gt-other"><a href="#orElseGet-Supplier-lt-extends-T-gt-other" class="headerlink" title="orElseGet(Supplier&lt;? extends T&gt; other)"></a>orElseGet(Supplier&lt;? extends T&gt; other)</h4><p>该方法和功能类似，不过和 orElse(T other) 方法不同的是， <code>Optional</code> 容器中的值为 <code>null</code>时返回的对象通过生产型函数接口来创建并返回</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> optionalUser1.orElseGet(() -&gt; <span class="keyword">new</span> <span class="title class_">User</span>());</span><br><span class="line">        System.out.println(user1 == user2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="orElseThrow-Supplier-lt-extends-X-gt-exceptionSupplier"><a href="#orElseThrow-Supplier-lt-extends-X-gt-exceptionSupplier" class="headerlink" title="orElseThrow(Supplier&lt;? extends X&gt; exceptionSupplier)"></a>orElseThrow(Supplier&lt;? extends X&gt; exceptionSupplier)</h4><p>该方法的逻辑和 <code>orElse(T other)</code>、<code>orElseGet(Supplier other)</code> 基本类似，不过当 <code>Optional</code> 容器的值为 <code>null</code> 时，会抛出生产型函数返回的异常对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        Optional&lt;User&gt; optionalUser1 = Optional.ofNullable(user1);</span><br><span class="line">        <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span> optionalUser1.orElseThrow(() -&gt; <span class="keyword">new</span> <span class="title class_">Exception</span>(<span class="string">&quot;抛出异常信息&quot;</span>));</span><br><span class="line">        System.out.println(user1 == user2);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="equals"><a href="#equals" class="headerlink" title="equals()"></a>equals()</h4><p>判断其他对象是否等于Optional</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//equals(Object obj):判断其他对象是否等于Optional</span></span><br><span class="line">        Optional&lt;String&gt; opt1 = Optional.of(<span class="string">&quot;Johnson&quot;</span>);</span><br><span class="line">        Optional&lt;String&gt; opt2 = Optional.of(<span class="string">&quot;Johnson&quot;</span>);</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> opt1.equals(opt2);</span><br><span class="line">        System.out.println(flag);<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/57459/">https://curry3035.gitee.io/posts/57459/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%BF%9B%E9%98%B6/">进阶</a><a class="post-meta__tags" href="/tags/optional%E7%B1%BB/">optional类</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/52957/" title="jdk8新特性--Method references"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">jdk8新特性--Method references</div></div></a></div><div class="next-post pull-right"><a href="/posts/9553/" title="jdk8新特性--Stream"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">jdk8新特性--Stream</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/55119/" title="每日一面--Files工具类"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-01</div><div class="title">每日一面--Files工具类</div></div></a></div><div><a href="/posts/34600/" title="面试一下--JUC入门"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-09-10</div><div class="title">面试一下--JUC入门</div></div></a></div><div><a href="/posts/11315/" title="实践一下--Spring Security"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-01</div><div class="title">实践一下--Spring Security</div></div></a></div><div><a href="/posts/40042/" title="每日一面--反射"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-01</div><div class="title">每日一面--反射</div></div></a></div><div><a href="/posts/56511/" title="实践一下--MySQL 优化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-04</div><div class="title">实践一下--MySQL 优化</div></div></a></div><div><a href="/posts/27951/" title="学习--ElasticSearch"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-29</div><div class="title">学习--ElasticSearch</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Optional-%E7%B1%BB%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">Optional 类简介</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Optional-%E7%B1%BB%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">Optional 类的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Optional-%E7%B1%BB%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.1.</span> <span class="toc-text">Optional 类介绍</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Optional-%E7%B1%BB%E7%9A%84%E7%94%B1%E6%9D%A5"><span class="toc-number">2.2.</span> <span class="toc-text">Optional 类的由来</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Optional-%E7%B1%BB%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">3.</span> <span class="toc-text">Optional 类常用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%A7%81%E6%9C%89%E6%9E%84%E9%80%A0"><span class="toc-number">3.1.</span> <span class="toc-text">私有构造</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#empty"><span class="toc-number">3.2.</span> <span class="toc-text">empty()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#of-T-value"><span class="toc-number">3.3.</span> <span class="toc-text">of (T value)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ofNullable-T-value-%E2%98%85"><span class="toc-number">3.4.</span> <span class="toc-text">ofNullable (T value) ★</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#get"><span class="toc-number">3.5.</span> <span class="toc-text">get()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#isPresent"><span class="toc-number">3.6.</span> <span class="toc-text">isPresent()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ifPresent-Consumer-lt-super-T-gt-consumer"><span class="toc-number">3.7.</span> <span class="toc-text">ifPresent(Consumer&lt;? super T&gt; consumer)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#filter-Predicate-lt-super-T-gt-predicate"><span class="toc-number">3.8.</span> <span class="toc-text">filter(Predicate&lt;? super T&gt; predicate)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#map-Function-lt-super-T-extends-U-gt-mapper"><span class="toc-number">3.9.</span> <span class="toc-text">map(Function&lt;? super T, ? extends U&gt; mapper)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#flatMap-Function-lt-super-T-Optional-gt-mapper"><span class="toc-number">3.10.</span> <span class="toc-text">flatMap(Function&lt;? super T, Optional&gt; mapper)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#orElse-T-other"><span class="toc-number">3.11.</span> <span class="toc-text">orElse(T other)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#orElseGet-Supplier-lt-extends-T-gt-other"><span class="toc-number">3.12.</span> <span class="toc-text">orElseGet(Supplier&lt;? extends T&gt; other)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#orElseThrow-Supplier-lt-extends-X-gt-exceptionSupplier"><span class="toc-number">3.13.</span> <span class="toc-text">orElseThrow(Supplier&lt;? extends X&gt; exceptionSupplier)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#equals"><span class="toc-number">3.14.</span> <span class="toc-text">equals()</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>